﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using JKF.BusinessLayer;
using JKF.BusinessLayer.BLL;
using JKF.Entities;
using JKF.Entities.Model;
using JKF.Substructure;
using SFWS.XHandler.Core;

namespace JKF.HandlerLayer.Sales
{
    public class Sales_nutritionHandler : AHttpHandler
    {
        #region Process
        public override void ProcessRequest()
        {
            try
            {
                this.HandleRequest(Utils.GetActionName);
            }
            catch (Exception ex)
            {
                //将错误抛到客户端(以Json格式)
                Utils.ToClient(true, ex.Message);
                AppLogger.Log(ex.Message, ex);  //写日志
            }
        }
        #endregion

        #region Manager
        private static bllSALES_NUTRITION salesNutritionMgr = new bllSALES_NUTRITION();
        private static bllCUSTOMER customerMgr = new bllCUSTOMER();
        private static bllPRODUCT productMgr = new bllPRODUCT();
        private static bllSYS_USER sysUserMgr = new bllSYS_USER();
        private static StringBuilder builder = new StringBuilder();
        #endregion

        #region Handler
        /// <summary>
        /// 添加/编辑
        /// </summary>
        [Exp2Client]
        public void EditSalesNutrition()
        {
            var opSuccess = false;
            var bEdit = false;
            var salesConsumeJson = JsonSerializer.Deserialize<SalesNutritionJson>(P("salesNutrition"));
            var nutritionInfo = BuildNutrition(salesConsumeJson);
            if (salesConsumeJson.NUTRITION_KEY.IsGuidB())
            {//Edit
                bEdit = true;
                nutritionInfo.NUTRITION_KEY = salesConsumeJson.NUTRITION_KEY.ToGuid();
                var serverModel = salesNutritionMgr.GetModel(nutritionInfo.NUTRITION_KEY);
                if (serverModel == null || (serverModel.STATUS == "9")) throw new Exception("待编辑项不存在.");
                //Do Update operation
                opSuccess = bllSALES_NUTRITION.UpdateSalesNutrition(nutritionInfo);
                var customer = customerMgr.GetModel(nutritionInfo.CUSTOMER_KEY);
                if (customer == null) throw new Exception("顾客不存在.");
                AppendLog(customer, serverModel, nutritionInfo, LogType.Edit);
            }
            else
            {
                //Add new
                nutritionInfo.NUTRITION_KEY = DB.HR.GetNewGuid().ToGuid();
                nutritionInfo.POINT_KEY = Guid.Empty;
                nutritionInfo.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY;
                nutritionInfo.STATUS = "1";
                nutritionInfo.SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE;
                nutritionInfo.UNIQUE_CODE = bllSALES_NUTRITION.GetSalesConsumeUniqueCode(nutritionInfo.SHOP_CODE);

                var outInfo = new STOCK_OUTinfo
                {
                    OUT_KEY = DB.HR.GetNewGuid().ToGuid(),
                    PRODUCT_KEY = nutritionInfo.PRODUCT_KEY,
                    PRODUCT_NUMS = 1,
                    SHOP_CODE = nutritionInfo.SHOP_CODE,
                    USER_CREATE = nutritionInfo.USER_CREATE,
                    OUT_NO = string.Format("{0}{1}", nutritionInfo.SHOP_CODE, DateTime.Now.ToString("yyyyMMddHHmmss")),
                    DATE_CREATE = DateTime.Now,
                    DATE_OUT = DateTime.Now,
                    DATE_UPDATE = DateTime.Now
                };

                var point = new POINT_LOGinfo()
                {
                    POINT_KEY = DB.HR.GetNewGuid().ToGuid(),
                    POINT_VALUE = nutritionInfo.ADD_POINT.HasValue ? nutritionInfo.ADD_POINT : 0,
                    CODE = "01",
                    WAY = "消费积分"
                };
                nutritionInfo.POINT_KEY = point.POINT_KEY;
                opSuccess = bllSALES_NUTRITION.InsertSalesNutrition(nutritionInfo, point, outInfo);
                var customer = customerMgr.GetModel(nutritionInfo.CUSTOMER_KEY);
                if (customer == null) throw new Exception("顾客不存在.");
                AppendLog(customer, nutritionInfo, null, LogType.Add);
            }

            if (opSuccess)
            {
                //重新获取数据
                nutritionInfo = salesNutritionMgr.GetModel(nutritionInfo.NUTRITION_KEY);
                var customerInfo = customerMgr.GetModel(nutritionInfo.CUSTOMER_KEY);
                var productInfo = productMgr.GetModel(nutritionInfo.PRODUCT_KEY);
                var sysUser = sysUserMgr.GetModel(nutritionInfo.USER_CREATE);
                Response.Write(new ResponseInf
                {
                    Success = true,
                    Data = new
                    {
                        NUTRITION_KEY = nutritionInfo.NUTRITION_KEY.ToString(),
                        UNIQUE_CODE = nutritionInfo.UNIQUE_CODE,
                        CARD_NO = customerInfo == null ? "" : customerInfo.CARD_NO,
                        CUSTOMER_KEY = customerInfo == null ? "" : customerInfo.CUSTOMER_KEY.ToString(),
                        CUSTOMER_NAME = customerInfo == null ? "" : customerInfo.NAME,
                        MOBILE = customerInfo == null ? "" : customerInfo.MOBILE,
                        PHONE = customerInfo == null ? "" : customerInfo.PHONE,
                        PRODUCT_KEY = nutritionInfo.PRODUCT_KEY,
                        PRODUCT_NAME = productInfo.NAME,
                        PRODUCT_MODEL = productInfo.MODEL,
                        NUMS = nutritionInfo.NUMS.ToStringNoValue(),
                        PRICE = nutritionInfo.PRICE.ToStringNoValue(),
                        MONEY = nutritionInfo.MONEY.ToStringNoValue(),
                        ADD_POINT = nutritionInfo.ADD_POINT.ToStringNoValue(),
                        STATUS_NAME = nutritionInfo.STATUS == "1" ? "有效" : "无效",
                        OPERATOR = sysUser == null ? "" : sysUser.REAL_NAME,
                        MEMO = nutritionInfo.MEMO,
                        PURCHASE_DATE = nutritionInfo.PURCHASE_DATE.ToShortDateLineFormat(),
                        DATE_CREATE = nutritionInfo.DATE_CREATE.ToShortDateLineFormat()
                    }
                }.ToJson());
                return;
            }
            throw new Exception(string.Format("{0}增值系列产品销售记录失败.", bEdit ? "编辑" : "添加"));
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        public void GetSalesNutritionByPage()
        {
            var obj = new PagerList();
            int pageCount = 0;
            int rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            var schPara = JsonSerializer.Deserialize<SearchOptions>(P("schOptions"));
            pageCurrent = int.TryParse(P("PageIndex"), out pageCurrent) ? pageCurrent : 0;
            pageSize = int.TryParse(P("PageSize"), out pageSize) ? pageSize : pageSize;
            var result = bllSALES_NUTRITION.GetSalesNutritionPaging(schPara.REGISTER_DATESTART, schPara.REGISTER_DATEEND, schPara.STATE,
                schPara.SHOP_CODE, schPara.filterBy, schPara.filterOperater, schPara.fiterText, bllSYS_USER.CurrentUser.USER_KEY.ToString(), pageCurrent, pageSize, ref pageCount, ref rowCount);

            if (P("isExport") != "1")
            {
                obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                      select new
                                                      {
                                                          NUTRITION_KEY = a.Field<Guid>("NUTRITION_KEY").ToString(),
                                                          UNIQUE_CODE = a.Field<string>("UNIQUE_CODE"),
                                                          CARD_NO = a.Field<string>("CARD_NO"),
                                                          CUSTOMER_NAME = a.Field<string>("CUSTOMER_NAME"),
                                                          MOBILE = a.Field<string>("MOBILE"),
                                                          PHONE = a.Field<string>("PHONE"),
                                                          PRODUCT_NAME = a.Field<string>("PRODUCT_NAME"),
                                                          PRODUCT_MODEL = a.Field<string>("PRODUCT_MODEL"),
                                                          NUMS = a.Field<int>("NUMS"),
                                                          PRICE = a.Field<decimal?>("PRICE").ToStringNoValue(),
                                                          MONEY = a.Field<decimal?>("MONEY").ToStringNoValue(),
                                                          ADD_POINT = a.Field<int?>("ADD_POINT").ToStringNoValue(),
                                                          STATUS_NAME = a.Field<string>("STATUS_NAME"),
                                                          OPERATOR = a.Field<string>("OPERATOR"),
                                                          MEMO = a.Field<string>("MEMO"),
                                                          EDITSHOW = a.Field<int>("isLock") > 0 ? "none" : "",
                                                          PURCHASE_DATE = a.Field<DateTime?>("PURCHASE_DATE").ToShortDateLineFormat(),
                                                          DATE_CREATE = a.Field<DateTime>("DATE_CREATE").ToShortDateString()
                                                      }).ToList();
                obj.RowCount = rowCount;
                obj.PageCount = pageCount;
                ResponseJsonObject = obj;
            }
            else
            {
                if (result == null) return;
                IDictionary<string, string> columns = new Dictionary<string, string>();
                columns.Add("CARD_NO", "顾客卡号");
                columns.Add("CUSTOMER_NAME", "姓名");
                columns.Add("MOBILE", "手机");
                columns.Add("UNIQUE_CODE", "销售单号");
                columns.Add("PRODUCT_NAME", "产品名称");
                columns.Add("NUMS", "数量");
                columns.Add("PRICE", "单价");
                columns.Add("MONEY", "实收金额");
                columns.Add("ADD_POINT", "增加积分");
                columns.Add("DATE_CREATE", "录入日期");
                columns.Add("MEMO", "备注");
                Excel.Export("增值系列产品销售记录", result, columns, Response, Excel.PageType.handler);
            }
        }

        /// <summary>
        /// 获取顾客营养系列销售记录
        /// </summary>
        public void GetSalesNutritionByCustomer()
        {
            var customerKey = P("customerKey");
            if (!customerKey.IsGuidB()) throw new Exception("顾客编号格式不正确.");
            var obj = new PagerList();
            var pageCount = 0;
            var rowCount = 0;
            var pageCurrent = 0;
            var pageSize = 20;
            pageCurrent = int.TryParse(P("PageIndex"), out pageCurrent) ? pageCurrent : 0;
            pageSize = int.TryParse(P("PageSize"), out pageSize) ? pageSize : pageSize;

            var result = bllSALES_NUTRITION.GetSalesNutritionOfCustomerPaging(customerKey,
                                                                              bllSYS_USER.CurrentUser.USER_KEY.ToString(),
                                                                              pageCurrent, pageSize, ref pageCount,
                                                                              ref rowCount);

            obj.Entity = null == result ? null : (from a in result.AsEnumerable()
                                                  select new
                                                  {
                                                      NUTRITION_KEY = a.Field<Guid>("NUTRITION_KEY").ToString(),
                                                      UNIQUE_CODE = a.Field<string>("UNIQUE_CODE"),
                                                      CARD_NO = a.Field<string>("CARD_NO"),
                                                      CUSTOMER_NAME = a.Field<string>("CUSTOMER_NAME"),
                                                      MOBILE = a.Field<string>("MOBILE"),
                                                      PHONE = a.Field<string>("PHONE"),
                                                      PRODUCT_NAME = a.Field<string>("PRODUCT_NAME"),
                                                      PRODUCT_MODEL = a.Field<string>("PRODUCT_MODEL"),
                                                      NUMS = a.Field<int>("NUMS"),
                                                      PRICE = a.Field<decimal?>("PRICE").ToStringNoValue(),
                                                      MONEY = a.Field<decimal?>("MONEY").ToStringNoValue(),
                                                      ADD_POINT = a.Field<int?>("ADD_POINT").ToStringNoValue(),
                                                      STATUS_NAME = a.Field<string>("STATUS_NAME"),
                                                      OPERATOR = a.Field<string>("OPERATOR"),
                                                      MEMO = a.Field<string>("MEMO"),
                                                      PURCHASE_DATE = a.Field<DateTime?>("PURCHASE_DATE").ToShortDateLineFormat(),
                                                      DATE_CREATE = a.Field<DateTime>("DATE_CREATE").ToShortDateString()
                                                  }).ToList();
            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;

        }

        /// <summary>
        /// 获得顾客购买记录Customer Info View
        /// </summary>
        [Exp2Client]
        public void GetNutritionByCustomer()
        {
            var customerKey = P("customerKey");
            if (!customerKey.IsGuidB()) throw new Exception("顾客编号格式不正确.");

            Response.Write(new ResponseInf
            {
                Success = true,
                Data = (from a in bllSALES_NUTRITION.GetNutritionByCustomer(customerKey, bllSYS_USER.CurrentUser.USER_KEY.ToString()).AsEnumerable()
                        select new
                        {
                            NUTRITION_KEY = a.Field<Guid>("NUTRITION_KEY").ToString(),
                            UNIQUE_CODE = a.Field<string>("UNIQUE_CODE"),
                            CARD_NO = a.Field<string>("CARD_NO"),
                            CUSTOMER_NAME = a.Field<string>("CUSTOMER_NAME"),
                            MOBILE = a.Field<string>("MOBILE"),
                            PHONE = a.Field<string>("PHONE"),
                            PRODUCT_NAME = a.Field<string>("PRODUCT_NAME"),
                            PRODUCT_MODEL = a.Field<string>("PRODUCT_MODEL"),
                            NUMS = a.Field<int>("NUMS"),
                            PRICE = a.Field<decimal?>("PRICE").ToStringNoValue(),
                            MONEY = a.Field<decimal?>("MONEY").ToStringNoValue(),
                            ADD_POINT = a.Field<int?>("ADD_POINT").ToStringNoValue(),
                            STATUS_NAME = a.Field<string>("STATUS_NAME"),
                            OPERATOR = a.Field<string>("OPERATOR"),
                            MEMO = a.Field<string>("MEMO"),
                            //EDITSHOW = a.Field<int>("isLock") > 0 ? "none" : "",
                            PURCHASE_DATE = a.Field<DateTime?>("PURCHASE_DATE").ToShortDateLineFormat(),
                            DATE_CREATE = a.Field<DateTime>("DATE_CREATE").ToShortDateString()
                        }).ToList()
            }.ToJson());
        }

        /// <summary>
        /// 删除营养系列销售记录
        /// </summary>
        [Exp2Client]
        public void RemoveNutrition()
        {
            var nutritionKey = P("nutritionKey");
            if (!nutritionKey.IsGuidB()) throw new Exception("增值系列产品销售记录编号格式不正确.");
            var dbModule = salesNutritionMgr.GetModel(nutritionKey.ToGuid());
            if (dbModule == null) throw new Exception("待删除的增值系列产品销售记录不存在.");
            var rslt = bllSALES_NUTRITION.RemoveSalesNutrition(nutritionKey);
            var customer = customerMgr.GetModel(dbModule.CUSTOMER_KEY);
            AppendLog(customer, dbModule, null, LogType.Delete);
            Response.Write(new ResponseInf
            {
                Success = (rslt == 1),
                Message = (rslt == 0) ? "删除增值系列产品销售记录失败." : ""
            }.ToJson());
        }
        #endregion

        #region ClientObj
        /// <summary>
        /// 依据客户端对象构建营养系列销售纪录
        /// </summary>
        /// <param name="nutritionJson"></param>
        /// <returns></returns>
        private SALES_NUTRITIONinfo BuildNutrition(SalesNutritionJson nutritionJson)
        {
            var t = new SALES_NUTRITIONinfo();
            int tmpInt;
            decimal tmpDeci;
            DateTime tmpDate;
            if (!nutritionJson.CUSTOMER_KEY.IsGuidB()) throw new Exception("请选择顾客.");
            t.CUSTOMER_KEY = nutritionJson.CUSTOMER_KEY.ToGuid();
            if (!nutritionJson.PRODUCT_KEY.IsGuidB()) throw new Exception("请选择产品名称.");
            t.PRODUCT_KEY = nutritionJson.PRODUCT_KEY.ToGuid();
            if (!decimal.TryParse(nutritionJson.PRICE, out tmpDeci)) throw new Exception("请输入单价.");
            t.PRICE = tmpDeci;
            if (!int.TryParse(nutritionJson.NUMS, out tmpInt)) throw new Exception("请输入数量.");
            t.NUMS = tmpInt;
            if (!decimal.TryParse(nutritionJson.MONEY, out tmpDeci)) throw new Exception("请输入实收金额.");
            t.MONEY = tmpDeci;
            t.ADD_POINT = (int.TryParse(nutritionJson.ADD_POINT, out tmpInt)) ? tmpInt : 0;
            if (!DateTime.TryParse(nutritionJson.PURCHASE_DATE, out tmpDate)) throw new Exception("请输入购买日期.");
            t.PURCHASE_DATE = tmpDate;
            t.MEMO = nutritionJson.MEMO;
            return t;
        }

        #endregion

        #region Class
        public class SearchOptions
        {
            public string REGISTER_DATESTART;
            public string REGISTER_DATEEND;
            public string STATE;
            public string SHOP_CODE;
            public string filterBy;
            public string filterOperater;
            public string fiterText;
        }

        public class SalesNutritionJson
        {
            public string NUTRITION_KEY;
            public string CUSTOMER_KEY;
            public string PRODUCT_KEY;
            public string PRICE;
            public string NUMS;
            public string MONEY;
            public string PURCHASE_DATE;
            public string ADD_POINT;
            public string MEMO;

        }
        #endregion

        #region Log
        private static string modeCode = "002004001";
        /// <summary>
        /// 添加营养系列部分日志
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="logType"></param>
        private void AppendLog(CUSTOMERinfo customer, SALES_NUTRITIONinfo from, SALES_NUTRITIONinfo to, LogType logType)
        {

            if (logType == LogType.Add)
            {
                bllSYS_LOG.SaveLog(modeCode,
                    "SALES_NUTRITION",
                    from.NUTRITION_KEY.ToString(),
                    string.Format("添加增值系列产品销售记录，顾客姓名:\"{0}\"  手机号:\"{1}\"", customer.NAME, customer.MOBILE),
                    "添加",
                    BusinessBase.ClientIp);
                return;
            }
            if (logType == LogType.Edit)
            {
                builder.Clear();
                builder.AppendFormat("修改增值系列产品销售记录，顾客姓名：\"{0}\"  手机号：\"{1}\"", customer.NAME, customer.MOBILE);
                var bChange = false;
                if (from.NUMS != to.NUMS)
                {
                    builder.AppendFormat("产品数量原值:\"{0}\"，现值:\"{1}\"", from.NUMS, to.NUMS);
                    bChange = true;
                }
                if (from.PRODUCT_KEY != to.PRODUCT_KEY)
                {
                    var prodMgr = new bllPRODUCT();
                    var prodF = prodMgr.GetModel(from.PRODUCT_KEY);
                    var prodT = prodMgr.GetModel(to.PRODUCT_KEY);
                    builder.AppendFormat("产品名称原值:\"{0}\"，现值:\"{1}\"", (prodF != null ? prodF.NAME : ""), (prodT != null ? prodT.NAME : ""));
                    bChange = true;
                }
                if (from.MONEY != to.MONEY)
                {
                    builder.AppendFormat("实收金额原值:\"{0}\"，现值:\"{1}\"", from.MONEY, to.MONEY);
                    bChange = true;
                }
                if (from.ADD_POINT != to.ADD_POINT)
                {
                    builder.AppendFormat("增加积分原值:\"{0}\"，现值:\"{1}\"", from.ADD_POINT, to.ADD_POINT);
                    bChange = true;
                }
                if (from.PURCHASE_DATE != to.PURCHASE_DATE)
                {
                    builder.AppendFormat("购买日期原值:\"{0}\"，现值:\"{1}\"", from.PURCHASE_DATE.ToFullDateTimeFormat(), to.PURCHASE_DATE.ToFullDateTimeFormat());
                    bChange = true;
                }
                if (bChange)
                {
                    bllSYS_LOG.SaveLog(modeCode,
                      "SALES_NUTRITION",
                      from.NUTRITION_KEY.ToString(),
                      builder.ToString(),
                      "修改",
                      BusinessBase.ClientIp);
                }
                return;
            }
            if (logType == LogType.Delete)
            {
                bllSYS_LOG.SaveLog(modeCode,
                      "SALES_NUTRITION",
                      from.NUTRITION_KEY.ToString(),
                      string.Format("删除增值系列产品销售记录，顾客姓名:\"{0}\"  手机号:\"{1}\"", customer.NAME, customer.MOBILE),
                      "删除",
                      BusinessBase.ClientIp);
            }/**/
        }
        #endregion
    }
}
